package com.heima.wemedia.gateway.filter;


import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否登录 登录了直接方形
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        //判断token是否真确 错误直接响应出去
        if (token == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //判断token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //是否过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i==1 || i == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //获取token里面的userid
            Long id = claimsBody.get("id", Long.class);
            if (id == null || id ==0) {
            //如果等于null说明还是没有登录
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //将id 发送到下面的服务器
            request.mutate().headers(httpHeaders -> httpHeaders.add("userId",id.toString())).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chain.filter(exchange);
    }


    //优先级 值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
